<script setup lang="ts">
import type { TANPANCHA_DATA_FILL_TYPE, TANPANCHA_DATA_SOURCE_TYPE } from '@/constant/modules/tanpancha'
import type { FormRules } from 'element-plus'

defineOptions({ name: 'PanchaData' })

const props = defineProps<{
  carbonInventoryId: number
  readonly?: boolean
}>()

const emit = defineEmits<{
  (e: 'saveSuccess'): void
  (e: 'open'): void
  (e: 'close'): void
}>()

const AsyncTableData = defineAsyncComponent(() => import('./async-table-data.vue'))

const visible = defineModel<boolean>({ required: true })

const tanpanchaStore = useTanpanchaStore()
const tableDataRef = ref<InstanceType<typeof AsyncTableData>>()
const tabId = ref()
const industryTotalOutput = ref(0)
const filter = ref({
  name: undefined,
  entryMethod: undefined,
  sourceType: undefined,
} as unknown as {
  name: string
  entryMethod: TANPANCHA_DATA_FILL_TYPE
  sourceType: TANPANCHA_DATA_SOURCE_TYPE
})
const rules: FormRules = {
  industryTotalOutput: [{ required: true, message: '请输入工业总产值' }],
}

async function clickSave() {
  const data = tableDataRef.value?.getData()
  carbonInventoryApi.saveCarbonInventoryDataEntryInfo(data).then(() => {
    ElMessage.success('保存成功')
    emit('saveSuccess')
  })
}

function clickSaveIndustryTotalOutput() {
  const isEmpty = (s: any) => s === undefined || s === null || s === ''
  if (isEmpty(industryTotalOutput.value)) {
    return ElMessage.error('请输入工业总产值')
  }
  carbonInventoryApi.saveCarbonInventoryIndustryTotalValue({
    carbonInventoryId: props.carbonInventoryId,
    grossIndustrialOutputValue: industryTotalOutput.value,
  }).then(() => {
    ElMessage.success('保存成功')
  })
}

function getIndustryTotalOutput() {
  carbonInventoryApi.queryCarbonInventoryIndustryTotalValueByCarbonInventoryId(
    props.carbonInventoryId,
  ).then(({ data }) => {
    industryTotalOutput.value = data.grossIndustrialOutputValue
  })
}

async function handleTabChange() {
  if (tabId.value === 1) {
    // 获取数据在异步子组件中
  }
  else if (tabId.value === 2) {
    getIndustryTotalOutput()
  }
}

watchEffect(() => {
  if (visible.value) {
    open()
  }
  else {
    close()
  }
})

onBeforeUnmount(() => {
  emit('close')
})

async function open() {
  tabId.value = 1
  visible.value = true
  emit('open')
}
async function close() {
  visible.value = false
  emit('close')
}
</script>

<template>
  <FullscreenModal v-model="visible">
    <div class="m-5 h-[calc(100%-2.5rem)] w-[calc(100%-2.5rem)] flex flex-col">
      <ElPageHeader class="flex-shrink-0 p-3" title="返回" content="数据管理" @back="visible = false" />
      <ElTabs v-model="tabId" type="card" @tab-change="handleTabChange">
        <ElTabPane label="设施/活动" :name="1" />
        <ElTabPane label="工业总产值" :name="2" />
      </ElTabs>
      <div v-if="tabId === 1" class="flex flex-auto flex-col overflow-auto pb-4">
        <ElForm inline class="flex items-center px-4">
          <ElFormItem label="设施/活动名称" class="!mb-0">
            <ElInput v-model="filter.name" clearable placeholder="请输入" />
          </ElFormItem>
          <ElFormItem label="数据填报方式" class="!mb-0">
            <ElSelect v-model="filter.entryMethod" clearable class="free !w-40">
              <ElOption v-for="item in tanpanchaStore.fillTypeOptions" :key="item.value" v-bind="item" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="活动数据来源" class="!mb-0">
            <ElSelect v-model="filter.sourceType" clearable class="free !w-40">
              <ElOption v-for="item in tanpanchaStore.sourceTypeOptions" :key="item.value" v-bind="item" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem v-if="!readonly" class="!mb-0 !ml-auto">
            <ElButton type="success" @click="clickSave">
              保存数据
            </ElButton>
          </ElFormItem>
        </ElForm>
        <Suspense>
          <AsyncTableData
            ref="tableDataRef"
            :carbon-inventory-id="carbonInventoryId" :readonly="readonly"
            :filter-name="filter.name" :filter-entry-method="filter.entryMethod"
            :filter-source-type="filter.sourceType"
          />
          <template #fallback>
            <div class="p-3 opacity-80">
              加载中...
            </div>
          </template>
        </Suspense>
      </div>
      <div v-else class="flex-auto overflow-auto p-4">
        <ElForm :model="{ industryTotalOutput }" :rules="rules">
          <ElFormItem label="工业总产值" class="w-50" required prop="industryTotalOutput">
            <ElInput v-if="!readonly" v-model="industryTotalOutput" clearable type="number" placeholder="请输入" />
            <div v-else>
              {{ industryTotalOutput }}
            </div>
          </ElFormItem>
          <ElFormItem v-if="!readonly">
            <ElButton type="primary" @click="clickSaveIndustryTotalOutput">
              保存
            </ElButton>
          </ElFormItem>
        </ElForm>
      </div>
    </div>
  </FullscreenModal>
</template>
